package apis

import (
	"LazyPig/database"
	"LazyPig/models"
	"LazyPig/pkg"
	"LazyPig/pkg/gredis"
	"LazyPig/pkg/reg"
	"LazyPig/pkg/res"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strings"
	"time"
)

// @Title login
// @Summary 用户登录
// @Description 登录
// @Param	name query string true "Name"
// @Param	pass query string true "Pass"
// @Success  200
// @router /login [get]
// @tags 用户中心
func Login(c *gin.Context)  {
	var u models.User
	if err := c.Bind(&u); err != nil {
		return
	}
	userInfo, err := models.Login(&u)
	if err != nil {
		c.JSON(res.Response(res.FAILED, nil, err.Error()))
		return
	}
	c.JSON(res.Response(res.SUCCESS, userInfo, "成功"))
}

func LoginWeb(c *gin.Context)  {
	var mobile = c.Query("mobile")
	var password = c.Query("password")
	user, _ := database.SqlDB.GetOne("SELECT * FROM user WHERE mobile = ? AND password = ?", mobile, password)
	if user == nil {
		c.JSON(res.FailedJson("用户名或密码错误"))
		return
	}
	token := pkg.CreatedToken(user["id"])
	c.JSON(res.SuccessJson(token))
}

// @Title Register
// @Summary 注册
// @Description 注册账号
// @Param mobile formData string true "用户名 2-6位"
// @Param password formData string true "密码 6-10位"
// @Success  200
// @router /register [post]
// @tags 用户中心
//func Register(c *gin.Context)  {
//	var u models.User
//	if err := c.Bind(&u); err != nil {
//		return
//	}
//	if err := models.Register(&u); err != nil {
//		c.JSON(res.FailedJson(err.Error()))
//		return
//	}
//	c.JSON(res.SuccessJson(""))
//}

func RefreshToken(c *gin.Context)  {
	token := c.Query("token")
	refreshToken := c.Query("refreshToken")
	uid,ok := pkg.CheckToken(token)
	if ok {
		key := fmt.Sprintf("REFRESHTOKEN-%v", uid)
		redisRefreshToken, err := gredis.Get(key)
		if err != nil || string(redisRefreshToken) != refreshToken {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		token := pkg.CreatedToken(uid)
		refreshToken := pkg.CreatedToken(fmt.Sprintf("%v-%s", uid, "1314"))
		var dayTime = 60 * 60 * 24
		gredis.Set(fmt.Sprintf("TOKEN-%v", uid), token, dayTime)
		gredis.Set(fmt.Sprintf("REFRESHTOKEN-%v", uid), refreshToken, dayTime * 30)
		data := make(map[string]interface{})
		data["token"] = token
		data["refreshToken"] = refreshToken
		c.JSON(res.SuccessJson(data))
	} else {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}
}

// @Title SendSmsCode
// @Summary 发送验证码
// @Description
// @Param	mobile query string	true "Mobile"
// @Success  200
// @router /user/sendSmsCode [get]
// @tags 用户中心
func SendSmsCode(c *gin.Context)  {
	rand.Seed(time.Now().UnixNano())
	code := rand.Intn(1000000)

	mobile := c.Query("mobile")

	if mobile == "" || !reg.RegexpTest(reg.Mobile, mobile) {
		c.JSON(res.FailedJson("手机号格式错误"))
		return
	}

	_, err := gredis.Get("smsLoginTime_" + mobile)

	if err == nil {
		c.JSON(res.FailedJson("请勿重复获取验证码"))
		return
	}

	msg := fmt.Sprintf("【⑦零八科技】您的验证码： %d , " +
		"您正在使用手机尾号%s进行手机绑定，注意保密！",code, mobile[len(mobile)-4:])

	data := strings.NewReader("needstatus=true&resptype=json&account=13650595084&&pswd=MScyh0309&mobile=" + mobile + "&msg=" + msg)
	response, err := http.Post("http://114.55.176.84:80/msg/HttpBatchSendSM","application/x-www-form-urlencoded; charset=UTF-8", data)
	defer response.Body.Close()
	if err != nil {
		c.JSON(res.FailedJson(err.Error()))
		return
	}
	if response.StatusCode == 200 {
		//buf := new(bytes.Buffer)
		//buf.ReadFrom(response.Body)
		//s := buf.String()
		//fmt.Println(s)
		err = gredis.Set("smsLoginTime_" + mobile, code, 50)
		err = gredis.Set("smsLoginCode_" + mobile, code, 900)
		if err != nil {
			fmt.Println("redis=>" + err.Error())
			goto End
		}
		c.JSON(res.SuccessJson(""))
		return
	}
End:
	c.JSON(res.FailedJson("发送失败"))
}

// @Title GetUserInfo
// @Summary 获取用户信息
// @Description
// @Param token query string true "令牌"
// @Success  200
// @router /user/getInfo [get]
// @tags 用户中心
func GetUserInfo(c *gin.Context)  {
	var (
		uid interface{}
		userInfo interface{}
		err error
	)
	uid, _ = c.Get("uid")

	userInfo, err = models.GetUserInfo(uid.(float64))
	if err != nil {
		c.JSON(res.FailedJson(err.Error()))
		return
	}
	c.JSON(res.SuccessJson(userInfo))
}

func Test(c *gin.Context)  {
	//song := make(map[string]string)
	//song["path"] = "/pages/home/home"
	//bytesData, err := json.Marshal(song)
	//data := bytes.NewReader(bytesData)
	//response, err := http.Post("https://api.weixin.qq.com/wxa/getwxacode?access_token=30_au1j_ljm5nlAEOKCUIqzhAgLJHYjcZGIBi6wN6LeJx9YGakvWCJM6I6yC5tIKQPXL9PQeOVH6RL3s9AZXMS4-8g1TwwkCSQysncsPOCvT0PrjM9xSxqBc--YFziCiJXEFZUGyjAPcFLCT7sWIPUiABABIN","application/x-www-form-urlencoded; charset=UTF-8", data)
	//defer response.Body.Close()
	//if err != nil {
	//	c.JSON(http.StatusOK, res.GenFailedJson(err.Error()))
	//	return
	//}
	//if response.StatusCode == 200 {
	//	buf := new(bytes.Buffer)
	//	buf.ReadFrom(response.Body)
	//	err = ioutil.WriteFile("./statics/img/code.jpg", buf.Bytes(), 0666)
	//	fmt.Println(err)
	//	c.JSON(http.StatusOK, res.GenSuccessJson(""))
	//} else {
	//	c.JSON(http.StatusOK, res.GenFailedJson("发送失败"))
	//}
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(http.StatusBadRequest, "")
		return
	}
	name := file.Filename
	if err = c.SaveUploadedFile(file, "./statics/img/" + name); err != nil {
		c.JSON(http.StatusBadRequest, "")
		return
	}
	c.JSON(res.SuccessJson(name))
}

func GetPersonnel(c *gin.Context)  {
	rows, err := models.GetPersonnel()
	if err != nil {
		c.JSON(res.FailedJson(err.Error()))
		return
	}
	c.JSON(res.SuccessJson(rows))
}

func Password(c *gin.Context)  {
	oldPassword := c.Query("oldPassword")
	newPassword := c.Query("newPassword")
	uid, _ := c.Get("uid")
	user, _ := database.SqlDB.GetOne("SELECT * FROM user WHERE id = ? AND password = ?", uid, oldPassword)
	if user == nil {
		c.JSON(res.FailedJson("密码错误"))
		return
	}
	data := make(map[string]interface{})
	data["password"] = newPassword
	_, err := database.SqlDB.Update("user", fmt.Sprintf("id = %s", uid), data)
	if err != nil {
		c.JSON(res.FailedJson("修改失败"))
		return
	}
	c.JSON(res.SuccessJson(nil))
}